package czk.concrent.threadpool.ThreadPrepareAndWrapUp;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * 线程池的线程预处理和收尾工作对线程拒绝策略的影响
 *
 * @author chenzhangkun
 * @ClassName ThreadPrepareAndWrapUpRejectTion
 * @description: TODO
 * @date 2024年04月29日
 */
public class ThreadPrepareAndWrapUpRejection {
	private final static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
			64,
			64,
			0,
			TimeUnit.MINUTES,
			new ArrayBlockingQueue<>(32)
	) {
		@Override
		protected void afterExecute(Runnable r, Throwable t) {
			System.out.println("执行收尾工作了======");
			super.afterExecute(r, t);
		}
	};

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();

		for (int i = 0; i < 400; i++) {
			list.add(i);
		}
		for (int i = 0; i < 100; i++) {
			List<List<Integer>> partition = Lists.partition(list, 400 / 32);
			int size = partition.size();
			CountDownLatch countDownLatch = new CountDownLatch(size);
			for (int j = 0; j < size; j++) {
				// 一批一批往线程池塞任务，当上一批线程执行完成后，后面有收尾和准备工作，导致线程还没有被释放又赛任务导致出发拒绝策略
				threadPoolExecutor.execute(() -> {
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						countDownLatch.countDown();
					}
				});
			}

			try {
				countDownLatch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("===============>  详情任务 - 任务处理完成");
		}
		System.out.println("都执行完成了");
	}

}
